package com.miaomiao.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.miaomiao.domain.system.LoginUser;
import com.miaomiao.domain.system.User;
import com.miaomiao.exception.ServiceException;
import com.miaomiao.mapper.system.MenuMapper;
import com.miaomiao.mapper.system.RoleMapper;
import com.miaomiao.mapper.system.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if(loginName.matches("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$")){
            queryWrapper.eq(User::getEmail,loginName);
        }else{
            queryWrapper.eq(User::getUserName,loginName);
        }
        User user = userMapper.selectOne(queryWrapper);
        if(Objects.isNull(user)){
            throw new ServiceException("用户名或密码错误");
        }
        List<Boolean> roleStatus = roleMapper.getRoleStatusByUserId(user.getUserId());
        if(!roleStatus.contains(false)){
            throw new ServiceException("该账号所有角色已被禁用,请联系管理员");
        }

        //查询对应的权限
        List<String> list = menuMapper.selectPermsByUserId(user.getUserId());

        return new LoginUser(user,list);
    }
}
